/**
 * 剑指 Offer 22. 链表中倒数第k个节点
 * https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/
 */
const { createListNode } = require('../../libs/public');

/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
function getKthFromEnd(head, k) {
  let next = head;
  for (let i = 0; i < k; i += 1) {
    next = next.next;
  }
  let pre = head;
  while (next) {
    pre = pre.next;
    next = next.next;
  }
  return pre;
}

console.log(getKthFromEnd(createListNode([1, 2, 3, 4, 5]), 2).val === 4);
console.log(getKthFromEnd(createListNode([1, 2, 3, 4, 5, 6]), 3).val === 4);
